//
//  HMStatusViewModel.swift
//  Weibo
//
//  Created by ZhuDong on 16/5/25.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit


let originalContentLabelFont: UIFont = UIFont.systemFontOfSize(14)
class HMStatusViewModel: NSObject {
    static let emotionRegex = try! NSRegularExpression(pattern: "\\[.*?\\]", options: [])
    static let topicRegex = try! NSRegularExpression(pattern: "#.*?#", options: [])
    static let atSomeOneRegex = try! NSRegularExpression(pattern: "@\\w+", options: [])
    static let urlRegex = try! NSRegularExpression(pattern: "(http[s]{0,1})://[a-zA-Z0-9\\.\\-]+\\.([a-zA-Z]{2,4})(:\\d+)?(/[a-zA-Z0-9\\.\\-~!@#$%^&*+?:_/=<>]*)?", options: [])
    var url_iconView: NSURL?
    var verified_image: UIImage?
    var name: String?
    var mrank_image: UIImage?
    var mrank_imageIsHidden: Bool?
    var created_atText: String?
    var sourceText: String?
    var contentText: String?
    var  pic_urls: [HMPicture]?
    var comments_text: String?
    var reposts_text: String?
    var attitudes_text: String?
    var originalAttributeString: NSAttributedString?
    var retweetAttributeString: NSAttributedString?
    var status: HMStatus?{
        didSet{
           url_iconView = NSURL(string: status?.user?.profile_image_url ?? "")
            
            if status?.user?.verified == 1 {
                verified_image = UIImage(named: "avatar_enterprise_vip")
            }else{
                verified_image = nil
            }
            
            name = status?.user?.name
            if let mbrank = status?.user?.mbrank where mbrank > 0 && mbrank < 7 {
               mrank_image = UIImage(named: "common_icon_membership_level\(mbrank)")
                
            }else{
               mrank_image = nil
            }
            created_atText = NSDate.sinaDate(status?.created_at ?? "")?.fullDescription()
            sourceText = dealSourceText(status?.source ?? "")
            contentText = status?.text
            pic_urls = status?.pic_urls
            reposts_text = dealTitleCount(status?.reposts_count ?? 0, defaultText: "转发")
            comments_text = dealTitleCount(status?.comments_count ?? 0, defaultText: "评论")
            attitudes_text = dealTitleCount(status?.attitudes_count ?? 0, defaultText: "赞")
            originalAttributeString = dealTextString(status?.text ?? "")
            retweetAttributeString = dealTextString(status?.retweeted_status?.text ?? "")
        }
    }
    
}
extension HMStatusViewModel{
    func dealTitleCount(count: Int,defaultText: String) -> String {
        if count / 1000 <=  0 {
            return defaultText
        }else{
            let text = Double(count) / 1000
            return ("\(text)万")
        }
    }
}
extension HMStatusViewModel{
    func dealSourceText(statusStr: String)->String{
       //"<a href=\"http://weibo.com/\" rel=\"nofollow\">\U5fae\U535a weibo.com</a>"
        let startFlag = "\">"
        let endFlag = "</a>"
        let startRange = statusStr.rangeOfString(startFlag)
        let endRange = statusStr.rangeOfString(endFlag)
        if let start = startRange,end = endRange {
            let range = start.endIndex..<end.startIndex
            let str = statusStr.substringWithRange(range)
            return str
        }
        return ""
    }
}
extension HMStatusViewModel{
    func dealTextString(text:String) -> NSAttributedString{
        let results = HMStatusViewModel.emotionRegex.matchesInString(text, options: [], range: NSRange(location: 0,length: text.characters.count))
        let strM = NSMutableAttributedString(string: text)
        //TODO:为何要reverse?
        for result in results.reverse() {
            let range = result.rangeAtIndex(0)
            let emotionStr = (text as NSString).substringWithRange(range)
            if let emotion = findEmotionWithChs(emotionStr) {
                let font = originalContentLabelFont
                let imageText = HMTextAttachment.getImageTextWithEmotion(emotion, font: font)
                strM.replaceCharactersInRange(range, withAttributedString: imageText)
            }
        }
        strM.addAttributes([NSFontAttributeName:originalContentLabelFont], range: NSRange(location: 0,length: strM.length))
        addTopicAttribute(strM, regex: HMStatusViewModel.topicRegex)
        addTopicAttribute(strM, regex: HMStatusViewModel.atSomeOneRegex)
        addTopicAttribute(strM, regex: HMStatusViewModel.urlRegex)
        return strM
    }
    private func addTopicAttribute(attributeString:NSMutableAttributedString,regex: NSRegularExpression){
        let str = attributeString.string
        let results = regex.matchesInString(str, options: [], range: NSRange(location: 0,length: str.characters.count))
        for result in results{
            let range = result.rangeAtIndex(0)
            let border = YYTextBorder(fillColor: UIColor.redColor(), cornerRadius: 3)
            let highlighted = YYTextHighlight()
            highlighted.setColor(UIColor.yellowColor())
            highlighted.setBackgroundBorder(border)
            attributeString.yy_setTextHighlight(highlighted, range: range)
            attributeString.addAttributes([NSForegroundColorAttributeName:UIColor.blueColor()], range: range)
        }
        
    }
    private func findEmotionWithChs(chs:String) -> HMEmotion?{
        for p in HMEmotionManager.shareManager.packages{
            for emotions in p.sectionEmotions {
                let array = emotions.filter({ (em) -> Bool in
                    return chs == em.chs
                })
                if array.count > 0 {
                    return array.first!
                }
            }
        }
        return nil
    }
}